<template>
    <el-container class="jxc_stock_inventory_container">
        <el-main class="main">
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="searchForm"
                                @event="handleHeaderEvent">
                    <template slot="left_search">
                        <div class="search_item" style="margin-left: 10px;">
                            <el-alert :closable="false" style="padding: 6px 10px;">盘点操作流程：新建盘点单、审核、盘点、录入盘点结果、复核、生成盘盈盘亏出入库单</el-alert>
                        </div>
                    </template>
                    <template slot="right_search">
                        <el-select class="w100" style="margin-right: 5px;" v-model="searchForm.state"
                                   @change="getList(true)">
                            <el-option v-for="(item, index) in stateList" :key="index"
                                       :label="item.label" :value="item.value" />
                        </el-select>
                    </template>
                </headerTemplate>
                <div class="card_content">
                    <vxeTableTemplate :data="dataList" :options.sync="tableOptions"
                                      @event="handleTableEvent" />
                </div>
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import InventoryForm from "../dialog/InventoryForm";
import poiApi from "@common/api/poiApi";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "JxcStockInventory",
    data() {
        const _this = this;
        return {
            searchForm: {
                state: '',
            },
            warehouseList: [],
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            _this.getList();
                        },
                    },
                    {
                        id: "add",
                        icon: "fa fa-plus",
                        type: "primary",
                        show: true,
                        permission: 'jxc:stockInventory:save',
                        method: () => {
                            _this.openDialog(null, 'add');
                        },
                    },
                    {
                        id: "edit",
                        icon: "fa fa-pencil",
                        type: "success",
                        show: true,
                        permission: 'jxc:stockInventory:save',
                        method: () => {
                            _this.openDialog(null, 'edit');
                        },
                    },
                    {
                        id: "delete",
                        icon: "fa fa-trash-o",
                        type: "danger",
                        show: true,
                        permission: 'jxc:stockInventory:delete',
                        method: () => {
                            _this.deleteConfirm();
                        },
                    },
                    {
                        id: "audit",
                        label: '审核',
                        icon: "el-icon-top-right",
                        class: 'audit_btn',
                        show: true,
                        permission: 'jxc:stockInventory:audit',
                        method: () => {
                            _this.changeAuditState('audit');
                        },
                    },
                    {
                        id: "reAudit",
                        label: '反审',
                        icon: "el-icon-bottom-left",
                        class: 're_audit_btn',
                        show: true,
                        permission: 'jxc:stockInventory:reAudit',
                        method: () => {
                            _this.changeAuditState('reAudit');
                        },
                    },
                    {
                        id: "export",
                        type: "success",
                        show: true,
                        icon: "el-icon-download",
                        permission: 'jxc:stockInventory:export',
                        label: '导出',
                        class: 'export_btn',
                        method: () => {
                            _this.handleExport();
                        },
                    },
                    {
                        id: "print",
                        icon: 'el-icon-printer',
                        show: true,
                        label: '打印',
                        class: 'print_btn',
                        permission: "jxc:stockInventory:print",
                        btnType: 'print',
                        printType: 'stockInventory',
                        dropdownItems: [
                            {
                                command: 'printTemplate',
                                label: '打印模板',
                                divided: true,
                                icon: 'el-icon-s-tools',
                                permission: 'jxc:stockInventory:printTemplate'
                            },
                            {
                                command: 'printItem',
                                label: '打印配置项',
                                icon: 'el-icon-s-tools',
                                permission: 'jxc:stockInventory:printItem'
                            },
                        ],
                        method: command => {
                            _this.handlePrintEvent(command);
                        },
                    },
                ],
                toolbar_filter: [
                    { type: "text", field: "code", label: "盘点单号" },
                    { type: "daterange", field: "check_date", label: "盘点日期", style: { width: '200px' }, },
                    { type: "select", field: "warehouse_sid", label: "仓库", options: [] },
                ],
            },
            stateList: [
                { value: '', label: "状态" },
                { value: 0, label: "待审核" },
                { value: 1, label: "已审核" },
                { value: 2, label: "已完成" }
            ],
            dataList: [],
            selectionList: [],
            tableOptions: {
                ref: 'JxcStockInventoryTable',
                container: '.jxc_stock_inventory_container',
                multiSelect: true,
                columns: [
                    {
                        label: '盘点单号',
                        prop: 'code',
                        align: 'center',
                    },
                    {
                        label: '盘点日期',
                        prop: 'check_date',
                        align: 'center',
                    },
                    {
                        label: '盘点仓库',
                        prop: 'warehouse_name',
                        align: 'center',
                    },
                    {
                        label: '审核状态',
                        prop: 'state',
                        align: 'center',
                        formatter: (row) => {
                            let filter = this.stateList.filter((item) => {
                                return item.value === row.state
                            });
                            if (filter.length > 0) {
                                return filter[0].label;
                            }
                            return row.state;
                        }
                    },
                    {
                        label: '审核人',
                        prop: 'auditor_name',
                        align: 'center',
                        formatter(row) {
                            if (row.state === 0) {
                                return '';
                            }
                            return row.auditor_name;
                        },
                    },
                    {
                        label: '审核时间',
                        prop: 'audit_date',
                        align: 'center',
                        formatter(row) {
                            if (row.state === 0) {
                                return '';
                            }
                            return row.audit_date;
                        },
                    },
                    {
                        label: '是否已经生成出入库单',
                        prop: 'update_stock',
                        align: 'center',
                        minWidth: 118,
                        formatter: (row) => {
                            if (row.update_stock === 1) {
                                return "是";
                            } else {
                                return "否";
                            }
                        }
                    },
                    {
                        label: '生成出入库单时间',
                        prop: 'update_stock_date',
                        align: 'center',
                        minWidth: 100,
                    }
                ],
                operates: {
                    fixed: "right",
                    count: 3,
                    list: [
                        {
                            id: "info",
                            icon: "fa fa-info-circle",
                            type: "warning",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: '详情',
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'detail');
                            }
                        },
                        {
                            id: 'auth',
                            icon: 'fa fa-pencil',
                            type: 'success',
                            size: 'mini',
                            show: true,
                            permission: "jxc:stockInventory:save",
                            tooltip: {
                                content: '编辑',
                            },
                            filter(row) {
                                return row.state === 0;
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'edit');
                            }
                        },
                        {
                            id: 'inventoryResults',
                            icon: 'el-icon-edit-outline',
                            type: 'primary',
                            size: 'mini',
                            show: true,
                            permission: "jxc:stockInventory:enterResult",
                            tooltip: {
                                content: '录入盘点结果',
                            },
                            filter(row) {
                                return row.state === 1;
                            },
                            method: (index, row) => {
                                _this.openInventoryResultsDialog(row);
                            }
                        },
                        {
                            id: 'del',
                            icon: 'fa fa-trash-o',
                            type: 'danger',
                            size: 'mini',
                            show: true,
                            permission: "jxc:stockInventory:delete",
                            tooltip: {
                                content: '删除',
                            },
                            filter(row) {
                                return row.state === 0;
                            },
                            method: (index, row) => {
                                _this.deleteConfirm(row)
                            }
                        },
                        {
                            id: 'review',
                            icon: 'el-icon-circle-check',
                            type: 'primary',
                            size: 'mini',
                            show: true,
                            permission: "jxc:stockInventory:review",
                            tooltip: {
                                content: '复核',
                            },
                            filter(row) {
                                return row.state === 1 && row.update_stock === 0;
                            },
                            method: (index, row) => {
                                _this.openReviewDialog(row);
                            }
                        },
                        // {
                        //     id: 'updateStock',
                        //     icon: 'el-icon-refresh',
                        //     type: 'primary',
                        //     size: 'mini',
                        //     show: true,
                        //     permission: "jxc:stockInventory:execute",
                        //     tooltip: {
                        //         content: '更新库存',
                        //     },
                        //     filter(row) {
                        //         return row.state === 2 && row.update_stock === 0;
                        //     },
                        //     method: (index, row) => {
                        //         _this.updateStock(row);
                        //     }
                        // },
                        {
                            id: 'gen_in_out',
                            icon: 'el-icon-download',
                            type: 'primary',
                            size: 'mini',
                            show: true,
                            permission: "",
                            tooltip: {
                                content: '生成出入库单',
                            },
                            filter(row) {
                                return row.state === 2 && row.update_stock === 0;
                            },
                            method: (index, row) => {
                                _this.genInOutBill(row);
                            }
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                }
            },
        }
    },
    mounted() {
        this.init();
        let list = this.tableOptions.columns.map((item, index) => {
            return {
                field: item.prop,
                text: item.label,
                _index: index + 1,
            };
        });
        list = [{ field: 'index', text: '序号', _index: 0 }].concat(list);
        console.log(JSON.stringify(list).replace(/"/g, '\\"'));
    },
    methods: {
        handleHeaderEvent(event) {
            const _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        async init() {
            const _this = this;
            await _this.initWarehouseList();
            _this.getList(true);
        },
        initWarehouseList() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindJxcStockWarehouses, {
                nopage: '1',
            }).then(res => {
                _this.warehouseList = (res.data || []).map(item => {
                    return {
                        value: item.sid,
                        label: item.name,
                    }
                });
                _this.headerOption = $.extend({}, _this.headerOption, {
                    toolbar_filter: _this.resetToolbarFilterSelect(_this.headerOption.toolbar_filter, 'warehouse_sid', _this.warehouseList),
                });
            }).catch(() => {
            });
        },
        // 初始化获取盘点单清单
        getList(query) {
            const _this = this;
            if (query) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            _this.fetchData(_this.$api.API_FindJxcStockInventorys, queryData).then(result => {
                _this.dataList = result.data || [];
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, result);
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        openDialog(row, type) {
            const _this = this;
            if (type === 'edit' && row == null) {
                if (!_this.checkSelection(_this.selectionList, false)) {
                    return;
                }
                row = _this.selectionList[0];
            }
            if (!row) {
                row = {};
            }
            if (type === 'edit' && row.state === 2) {
                _this.$message.error(`盘点单：${ row.code } 已更新库存，无法编辑！`);
                return;
            }
            if (type === 'edit' && row.state === 1) {
                _this.$message.error(`盘点单：${ row.code } 已审核，请先反审核再编辑！`);
                return;
            }
            let detail = type === 'detail' || row.state === 1;
            _this.$dialog({
                title: '盘点单',
                width: '1200px',
                component: {
                    value: InventoryForm,
                    props: {
                        detail,
                        row,
                    },
                },
                hideConfirmBtn: detail,
                confirmed() {
                    _this.getList();
                },
            });
        },
        deleteConfirm(row) {
            const _this = this;
            if (row && row.state === 2) {
                _this.$message.error(`盘点单：${ row.code } 已更新库存，无法删除`);
                return;
            }
            let filter = _this.selectionList.filter(item => item.state === 2);
            if (_this.$utils.isNotEmptyList(filter)) {
                let codeList = filter.map(item => item.code);
                _this.$message.error(`盘点单：${ codeList.join('、') } 已更新库存，无法删除`);
                return;
            }
            _this.storeDispatch('jxc/handleDeleteData', {
                url: _this.$api.API_DeleteJxcStockInventorys,
                row,
                list: _this.selectionList,
                _vm: _this,
                msg_name: '盘点单',
                state_field:'state',
            }).then(res => {
                if (res) {
                    _this.getList();
                }
            });
        },
        changeAuditState(type) {
            const _this = this;
            let filter = _this.selectionList.filter(item => item.state === 2);
            if (_this.$utils.isNotEmptyList(filter)) {
                let codeList = filter.map(item => item.code);
                _this.$message.error(`盘点单：${ codeList.join('、') } 已复核，无法${ type === 'audit' ? '审核' : '反审' }`);
                return;
            }
            _this.storeDispatch('jxc/changeAuditState', {
                url: _this.$api.API_ChangeJxcStockInventoryAuditState,
                list: _this.selectionList,
                type,
                _vm: _this,
                msg_name: '盘点单',
            }).then(res => {
                if (res) {
                    _this.getList();
                }
            });
        },
        openReviewDialog(row) {
            const _this = this;
            _this.$dialog({
                title: '复核盘点单',
                width: '1200px',
                component: {
                    value: InventoryForm,
                    props: {
                        review: true,
                        row,
                    },
                },
                confirmed() {
                    _this.getList();
                },
            });
        },
        openInventoryResultsDialog(row) {
            const _this = this;
            _this.$dialog({
                title: '录入盘点结果',
                width: '1200px',
                component: {
                    value: InventoryForm,
                    props: {
                        dialog: true,
                        isImport: true,
                        row,
                    },
                },
                confirmed() {
                    _this.getList();
                },
            });
        },
        handleExport() {
            const _this = this;
            if (!_this.checkSelection(_this.selectionList, false)) {
                return;
            }
            if (_this.selectionList[0].update_stock === 1) {
                _this.$message.error(`盘点单：${ _this.selectionList[0].code } 已更新库存`);
                return;
            }
            poiApi.exportExcelTemplateCustom(_this.$api.EXPORT_TEMPLATE_NAME_INVENTORY, _this.$api.API_GetJxcStockInventoryBySid, {
                sid: _this.selectionList[0].sid,
            }, `盘点单-${ _this.selectionList[0].code }`);
        },
        updateStock(row) {
            const _this = this;
            _this.fetchData(_this.$api.API_SaveJxcStockInventory4UpdateStock, {
                ...row
            }).then(() => {
                _this.$message.success('盘点更新库存成功！');
                _this.getList();
            }).catch((error) => {
                _this.$message.success(error.message);
            });
        },
        genInOutBill(row) {
            const _this = this;
            _this.fetchData(_this.$api.API_GenJxcStockInventory4InOutBill, {
                ...row
            }).then(() => {
                _this.$message.success('生成出入库单成功！');
                _this.getList();
            }).catch((error) => {
                _this.$message.success(error.message);
            });
        },
        handlePrintEvent(command) {
            const _this = this;
            if (command === 'printTemplate') {
                _this.$router.push({
                    path: '/print/stockInventory',
                    query: {
                        name: '盘点单',
                    },
                });
                return;
            }
            if (command === 'printItem') {
                _this.$router.push({
                    path: '/printItem/stockInventory',
                    query: {
                        name: '盘点单',
                    },
                });
                return;
            }
            if (!_this.checkSelection(_this.selectionList, true)) {
                return;
            }
            _this.$PrintPreview({
                template: command.sid,
                data: _this.selectionList,
                fetch(data) {
                    return _this.fetchData(_this.$api.API_QueryJxcStockInventoryData4Print, {
                        sid_list: data.map(item => item.sid),
                    }).then(result => {
                        return result.data || [];
                    }).catch(() => {
                        return [];
                    });
                },
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.jxc_stock_inventory_container {
    width: 100%;
    height: 100%;
}
</style>
